package com.example.vue_shop.components.role.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.vue_shop.components.rights.entity.Rights;
import com.example.vue_shop.components.rights.entity.TreeRights;
import com.example.vue_shop.components.rights.service.RightsService;
import com.example.vue_shop.components.role.entity.Role;
import com.example.vue_shop.components.role.entity.TreeRole;
import com.example.vue_shop.components.role.service.RoleService;
import com.example.vue_shop.utils.ResultObj;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author lipengwei
 */
@RestController
@Api(tags = "权限管理")
public class RoleController {

    @Resource(name = "roleServiceImpl")
    private RoleService roleService;

    @Resource(name = "rightsServiceImpl")
    private RightsService rightsService;

    /**
     * 获取角色列表.
     *
     * @param pageNum  页数
     * @param pageSize 每页显示的数量
     */
    @GetMapping("/role/getRoleList")
    @ApiOperation("获取角色列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", defaultValue =
                    "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示的数量",
                    defaultValue = "10")
    })
    public ResultObj<List<TreeRole>> getRoleList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        ResultObj<List<TreeRole>> resultObj = new ResultObj<>();
        try {

            List<TreeRole> roleList = roleService.getRoleList(pageNum, pageSize);
            resultObj.setData(roleList);
            resultObj.setMessage("获取角色列表成功！");
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setStatus(false);
            resultObj.setMessage("获取角色列表失败！");
        }
        return resultObj;
    }


    /**
     * 根据roleid 删除权限信息.
     * @param roleId 角色id
     * @param rightsId 权限Id
     */
    @ApiOperation("删除角色对应的权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色Id"),
            @ApiImplicitParam(name = "rightsId", value = "权限Id")
    })
    @DeleteMapping("/role/{roleId}/rights/{rightsId}")
    public ResultObj<List<TreeRights>> delRoleRights(@PathVariable("roleId") int roleId,
                                           @PathVariable("rightsId") int rightsId) {
        ResultObj<List<TreeRights>> resultObj = new ResultObj<>();
        try {
            /*
             * 1.判断要删除的 rights 有没有下级权限，有则无法删除，没有则可以删除。
             * */
            List<Rights> rightsList = rightsService.getRightsList(roleId);
            AtomicBoolean flag = new AtomicBoolean(true);
            rightsList.forEach(rights -> {
                if (rightsId == rights.getParentId()) {
                    flag.set(false);
                }
            });

            if (flag.get()) {
                List<TreeRights> treeRightsList = roleService.delRoleRights(roleId, rightsId);
                resultObj.setData(treeRightsList);
                resultObj.setMessage("删除权限成功！");
            } else {
                resultObj.setStatus(false);
                resultObj.setMessage("此权限有子权限，请重新选择！");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setStatus(false);
            resultObj.setMessage("删除权限失败！");
        }
        return resultObj;
    }

    /**
     * 给角色添加权限.
     * @param roleId 角色Id
     * @param rightsIntIds 权限Id集合
     */
    @ApiOperation("给角色添加权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色Id"),
            @ApiImplicitParam(name = "rightsIntIds", value = "权限Id列表")
    })
    @PostMapping("/roles/{roleId}/addRoleRights")
    public ResultObj<String> addRoleRights(@PathVariable ("roleId") int roleId,
                                           @RequestBody String rightsIntIds) {
        ResultObj<String> resultObj = new ResultObj<>();
        try {
            System.out.println(roleId+"--------" + rightsIntIds);
            roleService.addRoleRights(roleId, rightsIntIds);
            resultObj.setMessage("角色新增权限成功！");
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setStatus(false);
            resultObj.setMessage("角色新增权限失败！");
        }
        return resultObj;
    }

    /**
     * 新增角色.
     * @param role 角色对象
     */
    @ApiOperation("新增角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色Id")
    })
    @PostMapping("/role/add")
    public ResultObj<String> addRole(@RequestBody Role role) {
        ResultObj<String> resultObj = new ResultObj<>();
        try {
            roleService.addRole(role);
            resultObj.setMessage("新增角色成功");
        }catch (Exception e) {
            e.printStackTrace();

            resultObj.setStatus(false);
            resultObj.setMessage("新增角色成功");
        }
        return resultObj;
    }

    /**
     * 获取所有角色列表.
     */
    @ApiOperation("获取所有角色列表")
    @GetMapping("/role/getAllRoleList")
    public ResultObj<List<Role>> getAllRoleList(){
        ResultObj<List<Role>> resultObj = new ResultObj<>();
        try {
            List<Role> allRoleList = roleService.getAllRoleList();
            resultObj.setData(allRoleList);
            resultObj.setMessage("获取全部角色列表成功！");
        }catch (Exception e) {
            e.printStackTrace();
            resultObj.setStatus(false);
            resultObj.setMessage("获取角色列表失败！");
        }

        return resultObj;
    }

    /**
     * 更新角色的权限.
     * @param userId 用户Id
     * @param roleIdJsonStr {"roleId":3}
     */
    @ApiOperation("更新角色的权限")
    @PutMapping("/role/{userId}/update")
    public ResultObj<String> updateUserRole(@PathVariable("userId") int userId,
                                            @RequestBody String roleIdJsonStr) {
        ResultObj<String> resultObj = new ResultObj<>();
        try {
            JSONObject jsonObject = JSONObject.parseObject(roleIdJsonStr);
            roleService.updateUserRole(userId, jsonObject.getIntValue("roleId"));
            resultObj.setMessage("更新用户角色成功！");
        } catch (Exception e) {
            e.printStackTrace();
            resultObj.setMessage("更新用户角色失败！");
            resultObj.setStatus(false);
        }
        return resultObj;
    }
}
